<template>
  <view class="production-settings-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-gray" :isBack="true">
      <block slot="content">生产设置</block>
    </cu-custom>

    <!-- 基础设置 -->
    <view class="settings-section margin-top bg-white">
      <view class="section-header padding">
        <text class="section-title">基础设置</text>
      </view>
      <view class="settings-list">
        <view class="setting-item padding border-bottom" @click="editWorkTypes">
          <view class="setting-info">
            <text class="setting-title">工种管理</text>
            <text class="setting-desc">管理生产工种类型</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="editWorkStations">
          <view class="setting-info">
            <text class="setting-title">工位管理</text>
            <text class="setting-desc">配置生产工位信息</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="editEquipments">
          <view class="setting-info">
            <text class="setting-title">设备管理</text>
            <text class="setting-desc">管理生产设备档案</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding" @click="editQualityStandards">
          <view class="setting-info">
            <text class="setting-title">质量标准</text>
            <text class="setting-desc">设置产品质量检查标准</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
      </view>
    </view>

    <!-- 流程设置 -->
    <view class="settings-section margin-top bg-white">
      <view class="section-header padding">
        <text class="section-title">流程设置</text>
      </view>
      <view class="settings-list">
        <view class="setting-item padding border-bottom" @click="editProcessTemplates">
          <view class="setting-info">
            <text class="setting-title">工艺模板</text>
            <text class="setting-desc">管理生产工艺流程模板</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="editApprovalFlow">
          <view class="setting-info">
            <text class="setting-title">审批流程</text>
            <text class="setting-desc">配置计划和任务审批流程</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding" @click="editExceptionFlow">
          <view class="setting-info">
            <text class="setting-title">异常处理流程</text>
            <text class="setting-desc">设置异常上报和处理流程</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
      </view>
    </view>

    <!-- 通知设置 -->
    <view class="settings-section margin-top bg-white">
      <view class="section-header padding">
        <text class="section-title">通知设置</text>
      </view>
      <view class="settings-list">
        <view class="setting-item padding border-bottom">
          <view class="setting-info">
            <text class="setting-title">任务提醒</text>
            <text class="setting-desc">开启任务开始和截止提醒</text>
          </view>
          <switch :checked="notificationSettings.taskReminder" 
                  @change="onTaskReminderChange" 
                  color="#1890ff"></switch>
        </view>
        
        <view class="setting-item padding border-bottom">
          <view class="setting-info">
            <text class="setting-title">质量异常通知</text>
            <text class="setting-desc">质量检查异常时推送通知</text>
          </view>
          <switch :checked="notificationSettings.qualityAlert" 
                  @change="onQualityAlertChange" 
                  color="#1890ff"></switch>
        </view>
        
        <view class="setting-item padding border-bottom">
          <view class="setting-info">
            <text class="setting-title">设备故障通知</text>
            <text class="setting-desc">设备故障时推送通知</text>
          </view>
          <switch :checked="notificationSettings.equipmentAlert" 
                  @change="onEquipmentAlertChange" 
                  color="#1890ff"></switch>
        </view>
        
        <view class="setting-item padding">
          <view class="setting-info">
            <text class="setting-title">计划变更通知</text>
            <text class="setting-desc">生产计划变更时推送通知</text>
          </view>
          <switch :checked="notificationSettings.planChange" 
                  @change="onPlanChangeChange" 
                  color="#1890ff"></switch>
        </view>
      </view>
    </view>

    <!-- 系统参数 -->
    <view class="settings-section margin-top bg-white">
      <view class="section-header padding">
        <text class="section-title">系统参数</text>
      </view>
      <view class="settings-list">
        <view class="setting-item padding border-bottom" @click="editWorkingHours">
          <view class="setting-info">
            <text class="setting-title">工作时间</text>
            <text class="setting-desc">{{ systemParams.workingHours }}</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="editShiftSchedule">
          <view class="setting-info">
            <text class="setting-title">班次设置</text>
            <text class="setting-desc">{{ systemParams.shiftCount }}班制</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="editCapacitySettings">
          <view class="setting-info">
            <text class="setting-title">产能配置</text>
            <text class="setting-desc">设置各工种标准产能</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding" @click="editDataRetention">
          <view class="setting-info">
            <text class="setting-title">数据保留</text>
            <text class="setting-desc">{{ systemParams.dataRetention }}天</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
      </view>
    </view>

    <!-- 权限设置 -->
    <view class="settings-section margin-top bg-white">
      <view class="section-header padding">
        <text class="section-title">权限设置</text>
      </view>
      <view class="settings-list">
        <view class="setting-item padding border-bottom" @click="editRolePermissions">
          <view class="setting-info">
            <text class="setting-title">角色权限</text>
            <text class="setting-desc">配置不同角色的操作权限</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="editDataAccess">
          <view class="setting-info">
            <text class="setting-title">数据访问</text>
            <text class="setting-desc">设置数据访问范围控制</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding" @click="editOperationLog">
          <view class="setting-info">
            <text class="setting-title">操作日志</text>
            <text class="setting-desc">配置操作日志记录规则</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
      </view>
    </view>

    <!-- 数据管理 -->
    <view class="settings-section margin-top margin-bottom bg-white">
      <view class="section-header padding">
        <text class="section-title">数据管理</text>
      </view>
      <view class="settings-list">
        <view class="setting-item padding border-bottom" @click="backupData">
          <view class="setting-info">
            <text class="setting-title">数据备份</text>
            <text class="setting-desc">备份生产数据</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="exportData">
          <view class="setting-info">
            <text class="setting-title">数据导出</text>
            <text class="setting-desc">导出生产统计数据</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding border-bottom" @click="clearCache">
          <view class="setting-info">
            <text class="setting-title">清理缓存</text>
            <text class="setting-desc">清理应用缓存数据</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
        
        <view class="setting-item padding" @click="resetSettings">
          <view class="setting-info">
            <text class="setting-title">重置设置</text>
            <text class="setting-desc text-red">恢复默认设置</text>
          </view>
          <text class="cuIcon-right text-gray"></text>
        </view>
      </view>
    </view>

    <!-- 工作时间设置弹窗 -->
    <view v-if="showWorkingHoursModal" class="working-hours-modal" @click="showWorkingHoursModal = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header padding">
          <text class="text-lg text-bold">工作时间设置</text>
          <text class="cuIcon-close float-right" @click="showWorkingHoursModal = false"></text>
        </view>
        <view class="modal-form padding">
          <view class="form-item margin-bottom">
            <text class="form-label">开始时间</text>
            <picker mode="time" 
                    :value="workingHoursForm.startTime" 
                    @change="onStartTimeChange">
              <view class="form-picker">
                {{ workingHoursForm.startTime }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">结束时间</text>
            <picker mode="time" 
                    :value="workingHoursForm.endTime" 
                    @change="onEndTimeChange">
              <view class="form-picker">
                {{ workingHoursForm.endTime }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">午休开始</text>
            <picker mode="time" 
                    :value="workingHoursForm.lunchStart" 
                    @change="onLunchStartChange">
              <view class="form-picker">
                {{ workingHoursForm.lunchStart }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">午休结束</text>
            <picker mode="time" 
                    :value="workingHoursForm.lunchEnd" 
                    @change="onLunchEndChange">
              <view class="form-picker">
                {{ workingHoursForm.lunchEnd }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
        </view>
        <view class="modal-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="showWorkingHoursModal = false">取消</button>
          <button class="cu-btn bg-blue" @click="saveWorkingHours">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      notificationSettings: {
        taskReminder: true,
        qualityAlert: true,
        equipmentAlert: true,
        planChange: false
      },
      systemParams: {
        workingHours: '08:00-18:00',
        shiftCount: 2,
        dataRetention: 90
      },
      showWorkingHoursModal: false,
      workingHoursForm: {
        startTime: '08:00',
        endTime: '18:00',
        lunchStart: '12:00',
        lunchEnd: '13:00'
      }
    }
  },

  onLoad() {
    this.loadSettings()
  },

  methods: {
    async loadSettings() {
      try {
        const response = await mesApi.settings.getProductionSettings()
        this.notificationSettings = response.data.notifications
        this.systemParams = response.data.systemParams
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    },

    // 基础设置
    editWorkTypes() {
      uni.navigateTo({
        url: '/pages/production/settings/work-types'
      })
    },

    editWorkStations() {
      uni.navigateTo({
        url: '/pages/production/settings/work-stations'
      })
    },

    editEquipments() {
      uni.navigateTo({
        url: '/pages/production/settings/equipments'
      })
    },

    editQualityStandards() {
      uni.navigateTo({
        url: '/pages/production/settings/quality-standards'
      })
    },

    // 流程设置
    editProcessTemplates() {
      uni.navigateTo({
        url: '/pages/production/settings/process-templates'
      })
    },

    editApprovalFlow() {
      uni.navigateTo({
        url: '/pages/production/settings/approval-flow'
      })
    },

    editExceptionFlow() {
      uni.navigateTo({
        url: '/pages/production/settings/exception-flow'
      })
    },

    // 通知设置
    async onTaskReminderChange(e) {
      this.notificationSettings.taskReminder = e.detail.value
      await this.saveNotificationSettings()
    },

    async onQualityAlertChange(e) {
      this.notificationSettings.qualityAlert = e.detail.value
      await this.saveNotificationSettings()
    },

    async onEquipmentAlertChange(e) {
      this.notificationSettings.equipmentAlert = e.detail.value
      await this.saveNotificationSettings()
    },

    async onPlanChangeChange(e) {
      this.notificationSettings.planChange = e.detail.value
      await this.saveNotificationSettings()
    },

    async saveNotificationSettings() {
      try {
        await mesApi.settings.updateNotificationSettings(this.notificationSettings)
        uni.showToast({
          title: '设置已保存',
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    },

    // 系统参数
    editWorkingHours() {
      this.showWorkingHoursModal = true
    },

    editShiftSchedule() {
      uni.navigateTo({
        url: '/pages/production/settings/shift-schedule'
      })
    },

    editCapacitySettings() {
      uni.navigateTo({
        url: '/pages/production/settings/capacity'
      })
    },

    editDataRetention() {
      uni.showModal({
        title: '数据保留设置',
        editable: true,
        placeholderText: '请输入保留天数',
        success: async (res) => {
          if (res.confirm && res.content) {
            try {
              await mesApi.settings.updateDataRetention(parseInt(res.content))
              this.systemParams.dataRetention = parseInt(res.content)
              uni.showToast({
                title: '设置已保存',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    // 工作时间弹窗
    onStartTimeChange(e) {
      this.workingHoursForm.startTime = e.detail.value
    },

    onEndTimeChange(e) {
      this.workingHoursForm.endTime = e.detail.value
    },

    onLunchStartChange(e) {
      this.workingHoursForm.lunchStart = e.detail.value
    },

    onLunchEndChange(e) {
      this.workingHoursForm.lunchEnd = e.detail.value
    },

    async saveWorkingHours() {
      try {
        await mesApi.settings.updateWorkingHours(this.workingHoursForm)
        this.systemParams.workingHours = `${this.workingHoursForm.startTime}-${this.workingHoursForm.endTime}`
        this.showWorkingHoursModal = false
        uni.showToast({
          title: '设置已保存',
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    },

    // 权限设置
    editRolePermissions() {
      uni.navigateTo({
        url: '/pages/production/settings/role-permissions'
      })
    },

    editDataAccess() {
      uni.navigateTo({
        url: '/pages/production/settings/data-access'
      })
    },

    editOperationLog() {
      uni.navigateTo({
        url: '/pages/production/settings/operation-log'
      })
    },

    // 数据管理
    async backupData() {
      uni.showModal({
        title: '数据备份',
        content: '确定要备份当前生产数据吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '备份中...' })
              await mesApi.settings.backupData()
              uni.showToast({
                title: '备份成功',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '备份失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    },

    async exportData() {
      uni.showActionSheet({
        itemList: ['导出Excel', '导出CSV', '导出JSON'],
        success: async (res) => {
          try {
            uni.showLoading({ title: '导出中...' })
            const format = ['excel', 'csv', 'json'][res.tapIndex]
            await mesApi.settings.exportData(format)
            uni.showToast({
              title: '导出成功',
              icon: 'success'
            })
          } catch (error) {
            uni.showToast({
              title: '导出失败',
              icon: 'none'
            })
          } finally {
            uni.hideLoading()
          }
        }
      })
    },

    async clearCache() {
      uni.showModal({
        title: '清理缓存',
        content: '确定要清理应用缓存吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '清理中...' })
              await mesApi.settings.clearCache()
              uni.showToast({
                title: '清理完成',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '清理失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    },

    resetSettings() {
      uni.showModal({
        title: '重置设置',
        content: '确定要重置所有设置为默认值吗？此操作不可恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '重置中...' })
              await mesApi.settings.resetSettings()
              await this.loadSettings()
              uni.showToast({
                title: '重置完成',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '重置失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.production-settings-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.settings-section {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .section-header {
    border-bottom: 1rpx solid #f0f0f0;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .settings-list {
    .setting-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      &:last-child {
        border-bottom: none !important;
      }
      
      .setting-info {
        flex: 1;
        
        .setting-title {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .setting-desc {
          font-size: 24rpx;
          color: #666;
          
          &.text-red {
            color: #f5222d;
          }
        }
      }
      
      .cuIcon-right {
        font-size: 24rpx;
      }
    }
  }
}

.working-hours-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .modal-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .modal-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .modal-form {
      max-height: 60vh;
      overflow-y: auto;
      
      .form-item {
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 16rpx;
        }
        
        .form-picker {
          height: 80rpx;
          padding: 0 24rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #333;
        }
      }
    }
    
    .modal-actions {
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 16rpx;
      
      .cu-btn {
        flex: 1;
      }
    }
  }
}
</style>
